/**
 * 发布订阅模式
 * 开启worker线程、发起ajax请求
 * Time: 2020-12-16 dhc
 */
;(function(window){
    function WorkerCenter(){
        //储存函数字典
        this.handelMaps = {};
        this.worker = null;
        this.init();
    }
    WorkerCenter.prototype.init = function(){
        if(window.Worker){
            this.worker = new Worker('workerServer.js');
            this.worker.onmessage = this.onMessage.bind(this);
            this.worker.onerror = this.onError;
        }else{
            throw "对不起，请更换支持worker的浏览器."
        }
    }
    /***
     * 请求入口
     * 参数：obj (其他参数待完善...)
     *      - type
     *      - url
     *      - success
     *      - ......
     */
    WorkerCenter.prototype.http = function(obj){
        obj.hash = this.getHash();
        this.setHandelMap(obj);
        this.postMessage(obj);
    }
    WorkerCenter.prototype.getHash = function(){
        return ["w",new Date().getTime(), parseInt(Math.random()* 100000)].join("_");
    }
    WorkerCenter.prototype.setHandelMap = function(obj){
        if(typeof obj.success === 'function') this.handelMaps[obj.hash] = obj.success;
    }
    WorkerCenter.prototype.postMessage = function(obj){
        this.worker.postMessage(JSON.stringify(obj));
    }
    WorkerCenter.prototype.onMessage = function(evt){
        var result = JSON.parse(evt.data);
        if(typeof this.handelMaps[result.hash] === 'function'){
            this.handelMaps[result.hash](result.result);
        }
    }
    WorkerCenter.prototype.onError = function(e){
        console.warn("worker错误: ", e);
    }

    window.WorkerCenter = WorkerCenter;
})(window);